package parser

import (
	"path/filepath"
	"sort"
	"strings"

	"github.com/360EntSecGroup-Skylar/excelize"
)

var excel, version, pkg, codeOutputPath, dataOutputPath string
var clientPkg, clientCodeOutputPath, clientDataOutputPath string // 客户端

func Export(files, version, exportPath string) string {

	for _, txtPath := range strings.Split(files, "\r\n") {

		// todo 判断文件是不是没选择，路径是不是选错了
		excel = txtPath

		if excel == "配置文件拖到这里..." || excel == "" {
			return "请拖入配置文件!"
		}

		codeOutputPath = exportPath + `\` + version + `\Output\Server\Code\`
		dataOutputPath = exportPath + `\` + version + `\Output\Server\Data\Normal\`
		clientCodeOutputPath = exportPath + `\` + version + `\Output\Client\Code\`
		clientDataOutputPath = exportPath + `\` + version + `\Output\Client\Data\Normal\`

		fileName := strings.Split(filepath.Base(excel), ".")
		if len(fileName) > 1 {
			pkg = fileName[len(fileName)-2]
			clientPkg = pkg
			pkg = strings.ToLower(pkg)
		}

		xlsx, err := excelize.OpenFile(excel)
		if err != nil {
			return "打开文件错误"
		}

		var sheetSlice []string
		var sortKey []int
		mSheet := make(map[int]string) // index sheet名字
		for _, sheet := range xlsx.GetSheetMap() {
			index := xlsx.GetSheetIndex(sheet)
			mSheet[index] = sheet
			sortKey = append(sortKey, index)
		}
		sort.Ints(sortKey)
		for _, index := range sortKey {
			sheetSlice = append(sheetSlice, mSheet[index])
		}

		// 特殊格式的excel 语言和全局配置表
		if clientPkg == "SystemLanguage" || clientPkg == "ConfigValue" {
			// 数据解析
			if ret := DataParseSysLang(clientPkg, sheetSlice, xlsx); ret != "" {
				return "文件:" + txtPath + "\r\n" + ret
			}

			// // 特殊结构
			// if ret := StructParseConfigValueAndSysLang(clientPkg); ret != "" {
			// 	return "特殊结构 文件:" + txtPath + "\r\n" + ret
			// }


			if clientPkg == "ConfigValue" {
				// 服务端
				if ret := DataParseSysLangServer(sheetSlice, xlsx); ret != "" {
					return "文件:" + txtPath + "\r\n" + ret
				}
			}

			// continue
		}

		//数据解析
		if ret := DataParse(sheetSlice, xlsx); ret != "" {
			return "文件:" + txtPath + "\r\n" + ret
		}

		//结构解析
		if ret := StructParse(sheetSlice, xlsx); ret != "" {
			return "文件:" + txtPath + "\r\n" + ret
		}

	}

	return ""
}
